package utils

import (
	"errors"
	"net/http"
	"strings"
)

func httpDo(method string, url string, body string, headers map[string]string, params map[string]string) (*http.Response, error) {
	var request *http.Request
	var err error

	switch method {
	case http.MethodGet:
		request, err = http.NewRequest(http.MethodGet, url, nil)
	case http.MethodPost:
		request, err = http.NewRequest(http.MethodPost, url, strings.NewReader(body))
	case http.MethodPut:
		request, err = http.NewRequest(http.MethodPut, url, strings.NewReader(body))
	case http.MethodPatch:
		request, err = http.NewRequest(http.MethodPatch, url, strings.NewReader(body))
	case http.MethodDelete:
		request, err = http.NewRequest(http.MethodDelete, url, nil)
	default:
		return nil, errors.New("不支持的HTTP方法")
	}

	if err != nil {
		return nil, err
	}
	for k, v := range headers {
		request.Header.Set(k, v)
	}
	for k, v := range params {
		request.URL.Query().Add(k, v)
	}
	request.Header.Add("Content-Type", "application/json")
	return http.DefaultClient.Do(request)
}

func HttpGet(url string, headers map[string]string, params map[string]string) (*http.Response, error) {
	return httpDo(http.MethodGet, url, "", headers, params)
}

func HttpPost(url string, body string, headers map[string]string, params map[string]string) (*http.Response, error) {
	return httpDo(http.MethodPost, url, body, headers, params)
}

func HttpPut(url string, body string, headers map[string]string, params map[string]string) (*http.Response, error) {
	return httpDo(http.MethodPut, url, body, headers, params)
}
func HttpPatch(url string, body string, headers map[string]string, params map[string]string) (*http.Response, error) {
	return httpDo(http.MethodPatch, url, body, headers, params)
}
func HttpDelete(url string, headers map[string]string, params map[string]string) (*http.Response, error) {
	return httpDo(http.MethodDelete, url, "", headers, params)
}
